/**************************************************************
 *@ProjectName: blweibo
 *@FileName: WeiboEventService.java
 *@Date: 2011-5-31
 *@Copyright: 2011 www.hrbanlv.com Inc. All rights reserved.
 **************************************************************/
package com.zhiweibo;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;

import com.zhiweibo.models.StaticInfo;
import com.zhiweibo.models.UnreadNum;
import com.zhiweibo.util.Constant;
import com.zhiweibo.util.Helper;
import com.zhiweibo.util.HttpUtil;

/**
 * The Class WeiboEventService.
 * 
 * @author SunHaibin
 * @since Android 1.6
 * @history 2011-5-31
 */
public class WeiboEventService extends Service {

    /** The ntfmngr. */
    private static NotificationManager ntfmngr;

    /** The m notification. */
    private Notification mNotification;

    /** The timer. */
    private Timer timer;

    /** The handler. */
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            new CheckStatusTask().execute(0);
        }
    };

    /**
     * Del notify.
     */
    private void delNotify() {
        if (ntfmngr != null) {
            ntfmngr.cancelAll();
        }
        if (timer != null) {
            timer.cancel();
        }
        new UnreadNum();
        BaseActivity.handle.sendEmptyMessage(0);
    }

    /**
     * Del no.
     * 
     * @param id
     *            the id
     */
    public static void delNo(int id) {
        ntfmngr.cancel(id);
        int type = 1;
        switch (id) {
        case 10001:
            type = 1;
            UnreadNum.comment = 0;
            break;
        case 10002:
            type = 4;
            UnreadNum.message = 0;
            break;
        case 10003:
            type = 2;
            UnreadNum.atmsg = 0;
            break;
        case 10004:
            type = 8;
            UnreadNum.newfans = 0;
            break;
        }
        BaseActivity.handle.sendEmptyMessage(0);
        HttpUtil.delNo(Constant.RESET_COUNT + "?type=" + type);
    }

    /**
     * Dispatch message.
     */
    private void dispatchMessage() {
        mNotification = new Notification();
        mNotification.icon = R.drawable.logo;
        mNotification.when = 0;
        mNotification.defaults = 4;
        if (SettingsPref.isVibratorOn(this)) {
            mNotification.vibrate = new long[] { 80L, 80L };
        }
        if (SettingsPref.isAudioOn(this)) {
            mNotification.sound = Uri.parse("android.resource://com.zhiweibo/raw/notificationsound");
        }
        String str1 = "%d %s";
        String strNotice = null;
        int num[] = { UnreadNum.comment, UnreadNum.atmsg, UnreadNum.message, UnreadNum.newfans };
        boolean b1 = SettingsPref.isNotifyNewWeibo(this);
        boolean b2 = SettingsPref.isNotifyComment(this);
        boolean b3 = SettingsPref.isNotifyAt(this);
        boolean b4 = SettingsPref.isNotifyMessage(this);
        boolean b5 = SettingsPref.isNotifyFans(this);
        boolean b[] = { b2, b3, b4, b5 };
        if (b1 && UnreadNum.new_topic > 0) {
            if (MainTabActivity.handle != null) {
                MainTabActivity.handle.sendEmptyMessage(1);
            }
        }
        int id[] = { 10001, 10003, 10002, 10004 };
        int str[] = { R.string.main_msg_comment, R.string.main_msg_at, R.string.main_msg_message, R.string.main_msg_fan };
        for (int i = 0; i < 4; i++) {
            if (b[i] && num[i] > 0) {
                strNotice = String.format(str1, num[i], getString(str[i]));
                mNotification.tickerText = strNotice;
                mNotification.number = num[i];
                PendingIntent localPendingIntent;
                switch (i) {
                case 0:
                    Intent localIntent3 = new Intent(getApplicationContext(), MainTabActivity.class);
                    localIntent3.setAction("com.hbr.comment");
                    localPendingIntent = PendingIntent.getActivity(this, 0, localIntent3, 0);
                    break;
                case 1:
                    Intent localIntent4 = new Intent(getApplicationContext(), MainTabActivity.class);
                    localIntent4.setAction("com.hbr.at");
                    localPendingIntent = PendingIntent.getActivity(this, 0, localIntent4, 0);
                    break;
                case 2:
                    Intent localIntent5 = new Intent(getApplicationContext(), MainTabActivity.class);
                    localIntent5.setAction("com.hbr.message");
                    localPendingIntent = PendingIntent.getActivity(this, 0, localIntent5, 0);
                    break;
                default:
                    Intent localIntent1 = new Intent();
                    localIntent1.setClass(getApplicationContext(), UserWeiboAttentionFansList.class);
                    localIntent1.putExtra("mode", 3);
                    localIntent1.putExtra("uid", StaticInfo.mUid);
                    localPendingIntent = PendingIntent.getActivity(this, 0, localIntent1, 0);

                }
                mNotification.setLatestEventInfo(this, getString(R.string.app_name), strNotice, localPendingIntent);
                ntfmngr.notify(id[i], mNotification);
            } else {
                ntfmngr.cancel(id[i]);
            }
        }
        if (BaseActivity.handle != null) {
            BaseActivity.handle.sendEmptyMessage(0);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onBind(android.content.Intent)
     */
    @Override
    public IBinder onBind(Intent paramIntent) {
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onCreate()
     */
    @Override
    public void onCreate() {
        super.onCreate();
        if (TextUtils.isEmpty(StaticInfo.mUsername)) {
            stopSelf();
        } else {
            int inver = SettingsPref.getInterval(this);
            ntfmngr = (NotificationManager) getSystemService("notification");
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            }, 0, inver);

        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onDestroy()
     */
    @Override
    public void onDestroy() {
        delNotify();
        super.onDestroy();
    }

    /**
     * The Class CheckStatusTask.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class CheckStatusTask extends AsyncTask {

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected UnreadNum doInBackground(Object... paramArrayOfVoid) {
            return HttpUtil.getUnread(Helper.getString(WeiboEventService.this, "newId", "0"));
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Object paramUnreadNum) {
            dispatchMessage();
        }

    }

}
